package com.gitee.proxy.util;

import com.gitee.proxy.handler.proxy.ProxyHttpRequest;
import com.gitee.proxy.server.ServerConfig;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProxyRequestUtil {

    public static final Pattern uriPattern = Pattern.compile("^(http://|https://)?(?<host>[^/:]*)(?=:(?<port>\\d+))?(?<path>/.*)?");

    /**
     * 解析为代理请求
     */
    public static ProxyHttpRequest parserHttpProxyRequest(HttpRequest request, ServerConfig serverConfig) throws MalformedURLException {
        ProxyHttpRequest proxyHttpRequest = new ProxyHttpRequest(serverConfig.getHandler());
        String host = request.headers().get(HttpHeaderNames.HOST);
        if (host == null) {
            return null;
        }

        String uri = request.uri();
        LogUtil.info(ProxyRequestUtil.class, uri);
        if (uri.indexOf("/") > 0) {
            URL url = new URL(request.uri());
            request.setUri(url.getFile());
        }

        String[] hostArry = host.split(":");
        proxyHttpRequest.setHost(hostArry[0]);
        proxyHttpRequest.setPort(80);
        if (hostArry.length > 1) {
            proxyHttpRequest.setPort(Integer.parseInt(hostArry[1]));
        } else {
            Matcher matcher = uriPattern.matcher(uri);
            if (matcher.find()) {
                String hostName = matcher.group("host");
                String hostPort = matcher.group("port");
                if (hostName != null) {
                    proxyHttpRequest.setHost(hostName);
                }
                if (hostPort != null) {
                    proxyHttpRequest.setPort(Integer.parseInt(hostPort));
                }
            }
        }
        return proxyHttpRequest;
    }
}

